<template>
  <container>
    <!-- 类似于img标签 -->
    <sprite :texture="planeImg"></sprite>
  </container>
</template>

<script>
import planeImg from '@/assets/plane.png'
import { reactive, onMounted, onUnmounted } from 'vue'

export default {
  setup() {
    return {
      planeImg
    }
  }
}

export function usePlane({ onAttack }) {
  const planeInfo = reactive({
    x: 200,
    y: 600,
    width: 258,
    height: 364
  })

  const speed = 10
  // 键盘控制移动
  const handleMove = e => {
    switch (e.code) {
      case 'ArrowUp':
        planeInfo.y -= speed
        break

      case 'ArrowDown':
        planeInfo.y += speed
        break

      case 'ArrowRight':
        planeInfo.x += speed
        break

      case 'ArrowLeft':
        planeInfo.x -= speed
        break

      default:
        break
    }
  }

  // 攻击逻辑
  const handleAttack = e => {
    if (e.code === 'Space') {
      // 创建子弹
      onAttack &&
        onAttack({
          x: planeInfo.x + 100,
          y: planeInfo.y
        })
    }
  }

  onMounted(() => {
    window.addEventListener('keyup', handleMove)
    window.addEventListener('keyup', handleAttack)
  })

  onUnmounted(() => {
    window.removeEventListener('keyup', handleMove)
    window.removeEventListener('keyup', handleAttack)
  })

  return {
    planeInfo
  }
}
</script>
